package server

import (
	"database/sql"
	"encoding/json"
)

//微信code登录，返回新session
func code_login(tx *sql.Tx, jsonData string) (retstruct *ReturnStruct) {
	type CodeLoginInput struct {
		WxCode string `json:"code"`
	}
	var input CodeLoginInput
	err := json.Unmarshal([]byte(jsonData), &input)
	if err != nil {
		return FailRet(CodeParamError, err)
	}

	//请求微信后台登录url
	loginData, err := req_weixin_login(input.WxCode)

	//调用登录接口,因为随机数有小概率可能重复，所以调用三次
	var personId int = 0
	var wx_sessionkey string
	err = tx.QueryRow("select id, wx_session_key from tb_person where wx_openid = ?", loginData.OpenId).Scan(&personId, &wx_sessionkey)
	if err != nil {
		return DBErrReturn("select exist openid error", err)
	}

	if personId == 0 {
		result, _ := tx.Exec("insert into tb_person(wx_openid, wx_session_key) values(?, ?)", loginData.OpenId, loginData.SessionKey)
		count, _ := result.RowsAffected()
		if count == 0 {
			return SvrErrReturn("insert tb_person failed!")
		}
		personId64, _ := result.LastInsertId()
		personId = int(personId64)

	} else {
		if loginData.SessionKey != wx_sessionkey {
			result, _ := tx.Exec("update tb_person set wx_session_key = ? where id = ?", loginData.SessionKey, personId)
			count, _ := result.RowsAffected()
			if count == 0 {
				return SvrErrReturn("update tb_person failed!")
			}
		}
	}

	//插入session表
	for i := 0; i < 3; i++ {
		newSession := RandString(30) //生成新的session
		result, _ := tx.Exec("insert into tb_session(session_id, person_id, create_date) values(?, ?, CURDATE())", newSession, personId)
		count, _ := result.RowsAffected()
		if count == 0 {
			if i != 2 {
				continue
			} else {
				return SvrErrReturn("insert tb_session failed")
			}
		}

		type RetStruct struct {
			SessionId string `json:"session"`
		}
		return SuccRet(&RetStruct{newSession})
	}

	return SvrErrReturn("get exception ...")
}

//session登录, 返回用户信息
func session_login(tx *sql.Tx, person_id int64, jsonData string) *ReturnStruct {
	//查询第一个结果，看看是否返回正常

	//如果没有所属的家族就建立一个
	var count int
	err := tx.QueryRow("select count(*) from tb_family_member a join tb_family b on a.family_id = b.id where a.person_id = ?", person_id).Scan(&count)
	if err != nil {
		return FailRet(CodeDatabaseError, err)
	}
	if count == 0 {
		result, err := tx.Exec("insert into tb_family(name, create_person) values ('第一家', ?)", person_id)
		if err != nil {
			return DBErrReturn("新增家族失败", err)
		}
		new_family_id, err := result.LastInsertId()
		if err != nil {
			return DBErrReturn("获取新增的家族ID失败", err)
		}
		_, err = tx.Exec("insert into tb_family_member(family_id, person_id) values(?, ?)", new_family_id, person_id)
		if err != nil {
			return DBErrReturn("新增家族成员失败", err)
		}
	}

	//更新最近登录时间
	_, err = tx.Exec("update tb_person set last_login_timestamp = CURRENT_TIMESTAMP() where id = ?", person_id)
	if err != nil {
		return DBErrReturn("更新最新登录时间", err)
	}

	type Result struct {
		CurrUserId     int64                    `json:"curr_user_id"`   //当前人
		CurrFamilyId   int64                    `json:"curr_family_id"` //当前家族id
		CurrFamilyData []map[string]interface{} `json:"family_data"`    //当前家族的信息
	}
	var result Result
	result.CurrUserId = person_id

	//查询当前用户的默认家族，如果不存在，就取第一个作为默认
	var default_family int64
	err = tx.QueryRow("select IFNULL(default_family, 0) from tb_person where id = ?", person_id).Scan(&default_family)
	if err != nil {
		return DBErrReturn("获取默认家族失败", err)
	}
	if default_family == 0 {
		default_family, err = api_get_first_family(tx, person_id)
		if err != nil {
			return FailRet(CodeDatabaseError, err)
		}
		_, err = tx.Exec("update tb_person set default_family = ? where id = ?", default_family, person_id)
		if err != nil {
			return DBErrReturn("更新默认的家族失败", err)
		}
	}
	result.CurrFamilyId = default_family

	//再查询第一个家族的信息
	result.CurrFamilyData, err = api_get_family_info(tx, person_id, default_family)
	if err != nil {
		return FailRet(CodeDatabaseError, err)
	}
	return SuccRet(result)
}
